﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
using System.IO;
using VWise_DAO;

namespace VWise_Reporter
{
  public partial class MainForm : Form
  {

    const int W_LAST_RESULT_NONE = 0;
    const int W_LAST_RESULT_PERSONAL = 1;
    const int W_LAST_RESULT_VEHICLE = 2;

    CVWise_DAO_Access pVWise_DAO_Access = new CVWise_DAO_Access();
    int iLastResult = W_LAST_RESULT_NONE;
    int iLastIndex = -1;


    List<CPersonal> lListPersonal = null;
    List<CVehicle> lListVehicle = null;
    List<CMarkReportItem> lListReportItems = new List<CMarkReportItem>();
      
    public MainForm()
    {
      InitializeComponent();
    }

    void ChangeStateButtons(bool bState)
    {
      botonBuscar.Enabled = bState;
      botonGenerar.Enabled = bState;
      botonGeneraMultiple.Enabled = bState;
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
      
      //internal - configuracion de la consulta asincrona
      CLogProcessor.InitLog();
      pVWise_DAO_Access.Configure();
      
      //evento de finalizacion de consulta 
      pVWise_DAO_Access.OnVWise_DAO_Query += new CVWise_DAO_Access.VWise_DAO_QueryHandler(QueryHasFinished);

      ConfigureControlSizes();

        //Configurar carga combo box
      

      //List<TB_M_AREA> listaArea = (from d in bd.TB_M_AREAs
      //                                             select d).ToList();
      //comboArea.DataSource = listaArea;
      //comboArea.ValueMember = "N_COD_AREA";
      //comboArea.DisplayMember = "C_NOM_AREA";

      //List<TB_M_SECCION> listaSeccion = (from s in bd.TB_M_SECCIONs
      //                                   select s).ToList();
      //comboSeccion.DataSource = listaSeccion;
      //comboSeccion.ValueMember = "N_COD_SECCION";
      //comboSeccion.DisplayMember = "C_NOM_SECCION";
      var bd = new DHLDataContextDataContext();

      List<Department> listaDepartamento = (from d in bd.Departments
                                                   where d.department_manager_cd == null
                                                   select d).ToList();
      textArea.DataSource = listaDepartamento;
      textArea.ValueMember = "department_id";
      textArea.DisplayMember = "department_nm";

    }

    /// <summary>
    /// Gestor de Finalizacion de Resultados
    /// </summary>
    /// <param name="pQueryObject"></param>
    /// <param name="pEventArgs"></param>
    void QueryHasFinished(object pQueryObject, CVWise_DAO_EventArgs pEventArgs)
    {
      if (this.InvokeRequired)
      {
        CVWise_DAO_Access.VWise_DAO_QueryHandler d = new CVWise_DAO_Access.VWise_DAO_QueryHandler(QueryHasFinished);
        this.Invoke(d, pQueryObject, pEventArgs);
        return;
      }

      botonBuscar.Enabled = true;
    }

    void ConfigureControlSizes()
    {
      //picBoxLogo.Width = this.ClientSize.Width;
      tabControlResults.Width = this.ClientSize.Width - 12;
      tabControlResults.Height = this.ClientSize.Height - tabControlResults.Location.Y - 10;
      

    }

    private void MainForm_Resize(object sender, EventArgs e)
    {
      ConfigureControlSizes();
    }

    private void radioVehiculo_CheckedChanged(object sender, EventArgs e)
    {
      if (radioVehiculo.Checked)
      {
        textMarca.Enabled = true;
        textModelo.Enabled = true;
        textPlaca.Enabled = true;
        textArea.Enabled = false;
        checkBox1.Enabled = false;
        textArea.Enabled = false;
        comboArea.Enabled = false;
        comboSeccion.Enabled = false;
        textTipo.Enabled = true;    
      }
    }

    private void radioPersona_CheckedChanged(object sender, EventArgs e)
    {
      if (radioPersona.Checked)
      {
        textMarca.Enabled = false;
        textModelo.Enabled = false;
        textPlaca.Enabled = false;
        //textArea.Enabled = true;
        textArea.Enabled = false;
        comboArea.Enabled = false;
        comboSeccion.Enabled = false;
        checkBox1.Enabled = true;
        checkBox1.Checked = true;
        textTipo.Enabled = false;

      }
    }

    private void botonBuscar_Click(object sender, EventArgs e)
    {
        if (dateTimePickerHasta.Value.Subtract(dateTimePickerDesde.Value).Days < 90)
        {
            tabControlResults.SelectedIndex = 0;

            if (!ValidateTextAndData())
                return;

            picBoxFoto.Visible = false;
            ChangeStateButtons(false);
            textReportePara.Text = "";

            if (radioPersona.Checked)
            {
                //buscamos personas
                BuscarPersona();
            }
            else
            {
                //buscamos vehiculos
                BuscarVehicle();
            }
            ChangeStateButtons(true);
        }
        else
        {
            MessageBox.Show("El rango de fechas debe ser máximo de 3 meses");
        }  
      
    }

    bool ValidateTextAndData()
    {
      if (radioPersona.Checked)
      {
        if (textPaterno.Text == "" &&
           textMaterno.Text == "" &&
           textPrimerNombre.Text == "" &&
           textArea.SelectedValue == null
            && comboArea.SelectedValue==null
            && comboSeccion.SelectedValue==null)
        {
          //consulta invalida
          MessageBox.Show(this, "Debe al menos llenar un campo para efectuar la busqueda", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
          return false;
        }
      }
      else
      {
        ////buscamos vehiculos
        //if (textPaterno.Text == "" &&
        //    textMaterno.Text == "" &&
        //    textPrimerNombre.Text == "" &&
        //    textPlaca.Text == "" &&
        //    textMarca.Text == "" &&
        //    textModelo.Text == "")
        //{
        //  //consulta invalida
        //  MessageBox.Show(this, "Debe al menos llenar un campo para efectuar la busqueda", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        //  return false;
        //}
          return true;
      }
      
      return true;
    }

    void BuscarVehicle()
    {
      string szOutput;

      lListVehicle = null;
      treeViewResultados.Nodes.Clear();
      iLastResult = W_LAST_RESULT_NONE;
      
      //lListVehicle = pVWise_DAO_Access.SearchForVehicle(textPrimerNombre.Text,
      //                                                    textPaterno.Text,
      //                                                    textMaterno.Text,
      //                                                    textPlaca.Text,
      //                                                    textMarca.Text,
      //                                                    textModelo.Text);
      //lListVehicle = new List<CVehicle>();
      lListVehicle = GetListaVehiclelLinq();
        //Vamos a buscar dentro de la fecha si es que hay marcas de lo buscado
      

      if (lListVehicle == null)
      {
        MessageBox.Show(this, "No se encontraron resultados", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return;
      }

      if (lListVehicle.Count == 0)
      {
        MessageBox.Show(this, "No se encontraron resultados", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return;
      }

      foreach (CVehicle pVehicle in lListVehicle)
      {
          szOutput = "PLACA: " + pVehicle.szPlaca + " " +
                     "CARACTERISTICAS: " + pVehicle.szMarca + ", " + pVehicle.szModelo + ", " + pVehicle.szTipoVehiculo + " ";
                   //"CONDUCTOR: " + pVehicle.szConductor;

        treeViewResultados.Nodes.Add(szOutput);
      }
      iLastResult = W_LAST_RESULT_VEHICLE;
    }

    void BuscarPersona()
    {
      string szOutput;

      lListPersonal = null;
      treeViewResultados.Nodes.Clear();
      iLastResult = W_LAST_RESULT_NONE;
      iLastIndex = -1;

      //lListPersonal = pVWise_DAO_Access.SearchForPersonal(textPrimerNombre.Text,
      //                                                    textPaterno.Text,
      //                                                    textMaterno.Text,
      //                                                    textArea.SelectedValue.ToString());
      lListPersonal = GetListaPersonalLinq();

      if (lListPersonal == null)
      {
        MessageBox.Show(this, "No se encontraron resultados", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return;
      }

      if (lListPersonal.Count == 0)
      {
        MessageBox.Show(this, "No se encontraron resultados", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return;
      }

      foreach (CPersonal pPersonal in lListPersonal)
      {
        szOutput = pPersonal.szPatLastName + " " +
                   pPersonal.szMatlastName + ", " +
                   pPersonal.szFirstName + " [" +
                   pPersonal.szArea + "]";

        //if (pPersonal.codigoArea == (int)comboArea.SelectedValue && pPersonal.codigoSeccion == (int)comboSeccion.SelectedValue) 
        //{
            treeViewResultados.Nodes.Add(szOutput);
        //}  

        
      }
      iLastResult = W_LAST_RESULT_PERSONAL;
    }

    public List<CPersonal> GetListaPersonalLinq() 
    {
        var bd=new DHLDataContextDataContext();
        List<CPersonal> listaTemp = new List<CPersonal>();
        List<TB_M_PERSONA> listaPersona = new List<TB_M_PERSONA>(); 

        if (checkBox1.Checked == false)
        {
            //Vamos a buscar personas que hayan sido registradas en la tabla TB_CTR_Persona

            if (txtCodigo.Text.CompareTo("") != 0)
            {
                listaPersona = (from c in bd.TB_M_PERSONAs
                                where
                                c.CODIGOTAGSTR.ToString().CompareTo(txtCodigo.Text) == 0
                                select c).ToList();
            }
            else 
            {
                listaPersona = (from c in bd.TB_M_PERSONAs
                                where
                                c.C_PRI_NOMBRE.Contains(textPrimerNombre.Text)
                                && c.C_APE_PATERNO.Contains(textPaterno.Text)
                                && c.C_APE_MATERNO.Contains(textMaterno.Text)
                                //&& c.N_COD_PERSONA.ToString().CompareTo(txtCodigo.Text) == 0
                                select c).ToList();
            }

            


        }
        else 
        {
            listaPersona = (from c in bd.TB_M_PERSONAs
                                               where
                                               c.C_PRI_NOMBRE.Contains(textPrimerNombre.Text)
                                               && c.C_APE_PATERNO.Contains(textPaterno.Text)
                                               && c.C_APE_MATERNO.Contains(textMaterno.Text)
                                               && c.N_COD_DEP==(int)comboArea.SelectedValue
                                               && c.N_COD_SECCION==(int)comboSeccion.SelectedValue
                                               && c.N_COD_AREA==(int)textArea.SelectedValue
                                               select c).ToList();
        }
        foreach (var p in listaPersona)
        {
            //Tenemos que ver si la persona se encuentra en la tabla CTR_PERSONA
            List<TB_D_CTR_PERSONA> listaPersonasMarca = (from c in bd.TB_D_CTR_PERSONAs
                                                         where p.N_COD_PERSONA.CompareTo(c.N_COD_PERSONA)==0
                                                         && c.F_FECHA_MARCA>=dateTimePickerDesde.Value
                                                         && c.F_FECHA_MARCA<=dateTimePickerHasta.Value
                                                         select c).ToList();
            if (listaPersonasMarca.Count > 0) 
            {
                CPersonal cpersona = new CPersonal();
                cpersona.cargo = p.NAMLUGAR;
                cpersona.szArea = p.N_NOM_AREA + "/" + p.N_NOM_DEP + "/" + p.N_NAM_SECCION;
                cpersona.szFirstName = p.C_PRI_NOMBRE;
                cpersona.szMatlastName = p.C_APE_MATERNO;
                cpersona.szPatLastName = p.C_APE_PATERNO;
                cpersona.iPKCode = int.Parse(p.N_COD_PERSONA);
                cpersona.iCondition = p.N_EST_PERSONA;
                cpersona.codigoP = p.CODIGOTAGSTR;
                cpersona.szPhotoPath = p.FOTO;
                listaTemp.Add(cpersona);
            }
        }
        return listaTemp;

    }

    public List<CVehicle> GetListaVehiclelLinq() 
    {
        var bd = new DHLDataContextDataContext();
        List<CVehicle> listaTemp = new List<CVehicle>();
        List<TB_M_VEHICULO> listaVehiculos = new List<TB_M_VEHICULO>();

            //Vamos a buscar personas que hayan sido registradas en la tabla TB_CTR_Persona
            List<TB_M_VEHICULO> listaVehicles=new List<TB_M_VEHICULO>();
            if (txtCodigo.Text.CompareTo("") != 0)
            {
                //Busqueda por codigo de persona

                listaVehicles = (from vh in bd.TB_D_CTR_VEH_HANDs join ts in bd.TB_M_VEHICULOs
                                                              on vh.N_COD_VEHICULO  equals ts.N_COD_VEHICULODHL
                                where
                                vh.N_COD_PERSONA.ToString().CompareTo(txtCodigo.Text) == 0 &&
                                //fechas
                                 vh.F_FECHA_MARCA>=dateTimePickerDesde.Value
                                && vh.F_FECHA_MARCA<dateTimePickerHasta.Value
                                select ts).Distinct().ToList();
                //Si existe ese conductor en ese rango , hay q sacar los vehiculos
                
            }
            else
            {

                listaVehicles = (from vh in bd.TB_D_CTR_VEH_HANDs
                                 join ts in bd.TB_M_VEHICULOs
                                     on vh.N_COD_VEHICULO equals ts.N_COD_VEHICULODHL
                                 where
                                 ts.C_MAR_VEHICULO.Contains(textMarca.Text)
                                 && ts.C_MOD_VEHICULO.Contains(textModelo.Text)
                                 && ts.C_COD_PLACA.Contains(textPlaca.Text)
                                 && ts.C_TIP_VEHICULO.Contains(textTipo.Text)
                                     //fechas
                                 && vh.F_FECHA_MARCA >= dateTimePickerDesde.Value
                                 && vh.F_FECHA_MARCA <= dateTimePickerHasta.Value
                                 select ts).Distinct().ToList();
            }
            List<CVehicle> listaVehTemp = new List<CVehicle>();
            foreach (var p in listaVehicles)
             {
                    CVehicle cvehicle = new CVehicle();
                    cvehicle.iPKCode = (int)p.N_COD_VEHICULODHLINT;
                    cvehicle.szPlaca = p.C_COD_PLACA;
                    cvehicle.szTipoVehiculo = p.C_TIP_VEHICULO;
                    cvehicle.szMarca = p.C_MAR_VEHICULO;
                    cvehicle.szModelo = p.C_MOD_VEHICULO;
                    cvehicle.rutaFoto = p.C_RUTA;
                    listaVehTemp.Add(cvehicle);
             }
            return listaVehTemp;

    }

    private void treeViewResultados_AfterSelect(object sender, TreeViewEventArgs e)
    {

    }

    private void treeViewResultados_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
      CPersonal pPersonal = null;
      CVehicle pVehicle = null;


      switch(iLastResult)
      {
        case W_LAST_RESULT_PERSONAL:
          pPersonal = lListPersonal[e.Node.Index];
          if (File.Exists(pPersonal.szPhotoPath))
          {
            picBoxFoto.Visible = true;
            picBoxNoLogo.Visible = false;
            picBoxFoto.Load(pPersonal.szPhotoPath);
          }
          else
          {
            picBoxFoto.Visible = false;
            picBoxNoLogo.Visible = true;
          }
          textReportePara.Text = e.Node.Text;
          iLastIndex = e.Node.Index;
          break;

        case W_LAST_RESULT_VEHICLE:

          pVehicle= lListVehicle[e.Node.Index];
          if (File.Exists(pVehicle.rutaFoto))
          {
              picBoxFoto.Visible = true;
              picBoxNoLogo.Visible = false;
              picBoxFoto.Load(pVehicle.rutaFoto);
          }
          else
          {
              picBoxFoto.Visible = false;
              picBoxNoLogo.Visible = true;
          }
          
          textReportePara.Text = e.Node.Text;
          iLastIndex = e.Node.Index; 
          break;
      }
    }

    TimeSpan CalculateHorasDeTrabajo(CPersonal pPersonal, List<CMarkRegister> lListMarks)
    {
      TimeSpan tsTotalTime,tsWorkLabour,tsTempTime;
      DateTime dtLastTime,dtLastTimeIn, dtLastTimeOut;
      bool bInput = false, bOutput = false;

      dtLastTimeOut = new DateTime(0);
      dtLastTimeIn = new DateTime(0);

      tsTotalTime = new TimeSpan(0, 0, 0);
      tsWorkLabour = pPersonal.dtTimeOutRange - pPersonal.dtTimeInRange;

      foreach (CMarkRegister pMarkRegister in lListMarks)
      {
        dtLastTime = pMarkRegister.dtInOutTime;

        if (pMarkRegister.iFlagRegister == CPersonalManager.W_MARK_INGRESO)
        {
          dtLastTimeIn = dtLastTime;
          bInput = true;
        }
        else if (pMarkRegister.iFlagRegister == CPersonalManager.W_MARK_SALIDA)
        {
          dtLastTimeOut = dtLastTime;
          bOutput = true;
        }

        if (bInput && bOutput)
        {
          if (dtLastTimeOut >= dtLastTimeIn)
          {
            tsTempTime = dtLastTimeOut - dtLastTimeIn;
            bInput = false;
            bOutput = false;
            if (tsTempTime <= tsWorkLabour)
            {
              tsTotalTime += tsTempTime;
            }
          }
          else
          {
            bOutput = false;
          }
        }
      }

      return tsTotalTime;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ReporteUno();
    }

    void ReporteUno() 
    {

        //Vlido 3 meses
        if (dateTimePickerHasta.Value.Subtract(dateTimePickerDesde.Value).Days < 90)
        {
            //genera reporte
            CPersonal pPersonal = null;
            CVehicle pVehicle = null;
            List<CMarkRegister> lListMarks = null;
            CMarkReportItem pReportItem = null;
            TimeSpan tsTimeWorked;
            string szDates;

            ChangeStateButtons(false);
            tabControlResults.SelectedIndex = 1;

            if (iLastIndex == -1)
            {
                MessageBox.Show(this, "Seleccione un resultado para reportar", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                ChangeStateButtons(true);
                return;
            }

            dateTimePickerDesde.Value = dateTimePickerDesde.Value.Date +
                            (new TimeSpan(dateTimePickerDesde.Value.Hour, dateTimePickerDesde.Value.Minute, 0));
            dateTimePickerHasta.Value = dateTimePickerHasta.Value.Date +
                            (new TimeSpan(dateTimePickerHasta.Value.Hour, dateTimePickerHasta.Value.Minute, 59));


            if (dateTimePickerDesde.Value > dateTimePickerHasta.Value)
            {
                //busqueda por fechas invalida
                MessageBox.Show(this, "La fecha de inicio debe ser menor a la fecha final", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ChangeStateButtons(true);
                return;
            }
            szDates = dateTimePickerDesde.Value.ToString("yyyy/MM/dd hh:mm tt") + " - " + dateTimePickerHasta.Value.ToString("yyyy/MM/dd hh:mm tt");

            lListReportItems.Clear();

            switch (iLastResult)
            {
                case W_LAST_RESULT_PERSONAL:
                    pPersonal = lListPersonal[iLastIndex];
                    lListMarks = pVWise_DAO_Access.SearchMarks(CMarkRegister.VWISE_DHL_PERSONAL,
                                                               pPersonal.iPKCode,
                                                               dateTimePickerDesde.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                                                               dateTimePickerHasta.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                    //lListMarks = new List<CMarkRegister>();

                    //Por linq saco las marcas y el personal


                    if (lListMarks == null)
                    {
                        MessageBox.Show(this, "No se encontraron registros", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        ChangeStateButtons(true);

                        return;
                    }

                    if (lListMarks.Count == 0)
                    {
                        MessageBox.Show(this, "No se encontraron registros", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        ChangeStateButtons(true);
                        return;
                    }

                    //calculo de horas trabajadas
                    tsTimeWorked = CalculateHorasDeTrabajo(pPersonal, lListMarks);


                    foreach (CMarkRegister pMark in lListMarks)
                    {
                        pReportItem = new CMarkReportItem();

                        pReportItem.pMarkRegister = pMark;

                        pReportItem.pPersonal = pPersonal;

                        pReportItem.szDates = szDates;

                        pReportItem.tsTiempoTrabajado = tsTimeWorked;

                        lListReportItems.Add(pReportItem);
                    }

                    bindingSource1.DataSource = lListReportItems;
                    reportViewer1.Visible = true;
                    reportViewer2.Visible = false;
                    reportViewer3.Visible = false;
                    reportViewer1.RefreshReport();


                    break;

                case W_LAST_RESULT_VEHICLE:
                    pVehicle = lListVehicle[iLastIndex];

                    lListMarks = pVWise_DAO_Access.SearchMarks(CMarkRegister.VWISE_DHL_VEHICLE,
                                                               pVehicle.iPKCode,
                                                               dateTimePickerDesde.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                                                               dateTimePickerHasta.Value.ToString("yyyy-MM-dd HH:mm:ss"));

                    if (lListMarks == null)
                    {
                        MessageBox.Show(this, "No se encontraron registros", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        ChangeStateButtons(true);
                        return;
                    }

                    if (lListMarks.Count == 0)
                    {
                        MessageBox.Show(this, "No se encontraron registros", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        ChangeStateButtons(true);
                        return;
                    }


                    foreach (CMarkRegister pMark in lListMarks)
                    {
                        pReportItem = new CMarkReportItem();

                        pReportItem.pMarkRegister = pMark;

                        pReportItem.pVehicle = pVehicle;

                        pReportItem.szDates = szDates;

                        lListReportItems.Add(pReportItem);
                    }

                    CMarkReportItemBindingSource.DataSource = lListReportItems;
                    reportViewer2.Visible = true;
                    reportViewer1.Visible = false;
                    reportViewer2.RefreshReport();

                    break;
            }

            ChangeStateButtons(true);
        }
        else
        {
            MessageBox.Show("El rango de fechas debe ser máximo de 3 meses");
        }    
    }

    void ReporteGrupal() 
    {
        if (dateTimePickerHasta.Value.Subtract(dateTimePickerDesde.Value).Days < 90)
        {

            //procedimiento de generacion de multiples reportes
            //genera reporte
            CPersonal pPersonal = null;
            CVehicle pVehicle = null;
            List<CMarkRegister> lListMarks = null;
            CMarkReportItem pReportItem = null;
            string szDates, szName;
            int iCounter;
            TimeSpan tsTimeWorked;

            tabControlResults.SelectedIndex = 1;

            ChangeStateButtons(false);

            dateTimePickerDesde.Value = dateTimePickerDesde.Value.Date +
                            (new TimeSpan(dateTimePickerDesde.Value.Hour, dateTimePickerDesde.Value.Minute, 0));
            dateTimePickerHasta.Value = dateTimePickerHasta.Value.Date +
                            (new TimeSpan(dateTimePickerHasta.Value.Hour, dateTimePickerHasta.Value.Minute, 59));


            if (dateTimePickerDesde.Value > dateTimePickerHasta.Value)
            {
                //busqueda por fechas invalida
                MessageBox.Show(this, "La fecha de inicio debe ser menor a la fecha final", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ChangeStateButtons(true);
                return;
            }

            szDates = dateTimePickerDesde.Value.ToString("yyyy/MM/dd hh:mm tt") + " - " + dateTimePickerHasta.Value.ToString("yyyy/MM/dd hh:mm tt");

            if (lListVehicle != null)
            {
                if (lListVehicle.Count == 0)
                {
                    MessageBox.Show(this, "Seleccione resultados para reportar", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ChangeStateButtons(true);
                    return;
                }

            }

            //Destino de los reportes

            //DialogResult dResult = folderBrowserDialog1.ShowDialog();

            //if (dResult == DialogResult.Cancel)
            //{
            //    ChangeStateButtons(true);

            //    return;
            //}

            List<CMarkRegister> listaMarksTotal = new List<CMarkRegister>();
            List<CMarkRegister> listaMarcasVehicle = new List<CMarkRegister>();
            switch (iLastResult)
            {
                case W_LAST_RESULT_PERSONAL:
                    for (iCounter = 0; iCounter < lListPersonal.Count; iCounter++)
                    {
                        lListReportItems.Clear();
                        pPersonal = lListPersonal[iCounter];
                        lListMarks = pVWise_DAO_Access.SearchMarks(CMarkRegister.VWISE_DHL_PERSONAL,
                                                                   pPersonal.iPKCode,
                                                                   dateTimePickerDesde.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                                                                   dateTimePickerHasta.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                        listaMarksTotal.AddRange(lListMarks);
                        if (lListMarks == null)
                        {
                            MessageBox.Show(this, "No se encontraron registros para: " + pPersonal.szPatLastName +
                                                  " " + pPersonal.szMatlastName + ", " + pPersonal.szFirstName, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            continue;
                        }

                        //if (lListMarks.Count == 0)
                        //{
                        //  MessageBox.Show(this, "No se encontraron registros", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        //  botonGenerar.Enabled = true;
                        //  botonBuscar.Enabled = true;
                        //  return;
                        //}

                        //calculo de horas trabajadas
                        //CalculateHorasDeTrabajo

                    }

                    if (listaMarksTotal.Count == 0)
                    {
                        pReportItem = new CMarkReportItem();

                        pReportItem.pMarkRegister = new CMarkRegister(CMarkRegister.VWISE_DHL_PERSONAL);

                        pReportItem.pPersonal = pPersonal;

                        pReportItem.szDates = szDates;

                        pReportItem.tsTiempoTrabajado = new TimeSpan(0);

                        lListReportItems.Add(pReportItem);
                    }
                    else
                    {
                        //calculo de horas trabajadas
                        tsTimeWorked = CalculateHorasDeTrabajo(pPersonal, lListMarks);

                        foreach (CMarkRegister pMark in listaMarksTotal)
                        {
                            pReportItem = new CMarkReportItem();

                            pReportItem.pMarkRegister = pMark;

                            pReportItem.pPersonal = pPersonal;

                            pReportItem.szDates = szDates;

                            if (checkBox1.Checked)
                            {
                                pReportItem.Area_ReporteGrupal = textArea.Text + " / " + comboArea.Text + " / " + comboSeccion.Text;
                            }
                            else
                            {
                                pReportItem.Area_ReporteGrupal = "Todos";
                            }



                            pReportItem.tsTiempoTrabajado = tsTimeWorked;

                            lListReportItems.Add(pReportItem);
                        }
                    }

                    lListReportItems = lListReportItems.OrderBy(p => p.fechaMarca).ToList();

                    bindingSource1.DataSource = lListReportItems;
                    reportViewer3.Visible = true;
                    reportViewer2.Visible = false;
                    reportViewer1.Visible = false;
                    reportViewer3.RefreshReport();
                    //szName = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss") + pPersonal.szPatLastName + " " + pPersonal.szMatlastName +
                    //" " + pPersonal.szFirstName + ".xls";
                    //RenderReportC(folderBrowserDialog1.SelectedPath, szName, reportViewer1);

                    break;

                    

                case W_LAST_RESULT_VEHICLE:
                    for (iCounter = 0; iCounter < lListVehicle.Count; iCounter++)
                    {
                        lListReportItems.Clear();

                        pVehicle = lListVehicle[iCounter];

                        lListMarks = pVWise_DAO_Access.SearchMarks(CMarkRegister.VWISE_DHL_VEHICLE,
                                                                   pVehicle.iPKCode,
                                                                   dateTimePickerDesde.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                                                                   dateTimePickerHasta.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                        listaMarcasVehicle.AddRange(lListMarks);

                    }
                    if (lListMarks == null)
                    {
                        MessageBox.Show(this, "No se encontraron registros para: " + pVehicle.szPlaca, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        //continue;
                    }

                    if (listaMarcasVehicle.Count == 0)
                    {
                        pReportItem = new CMarkReportItem();

                        pReportItem.pMarkRegister = new CMarkRegister(CMarkRegister.VWISE_DHL_VEHICLE);

                        pReportItem.pVehicle = pVehicle;

                        pReportItem.szDates = szDates;

                        lListReportItems.Add(pReportItem);
                    }
                    else
                    {

                        foreach (CMarkRegister pMark in listaMarcasVehicle)
                        {
                            pReportItem = new CMarkReportItem();

                            pReportItem.pMarkRegister = pMark;

                            pReportItem.pVehicle = pVehicle;

                            pReportItem.szDates = szDates;


                            pReportItem.pVehicle.szMarca = "Todos";
                            pReportItem.pVehicle.szModelo = "";
                            pReportItem.pVehicle.szTipoVehiculo = "";
                            //pReportItem.szMarca_Modelo_prop = "Todos";
                            pReportItem.Codigo_prop = "Todos";

                            pReportItem.pVehicle.szPlaca= "Todos";


                            lListReportItems.Add(pReportItem);
                        }
                    }

                    lListReportItems = lListReportItems.OrderBy(p => p.fechaMarca).ToList();


                    CMarkReportItemBindingSource.DataSource = lListReportItems;
                    reportViewer2.RefreshReport();
                    reportViewer2.Visible = true;
                    reportViewer1.Visible = false;
                    reportViewer3.Visible = false;
                    //szName = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss") + pVehicle.szPlaca + ".xls";

                    //RenderReportC(folderBrowserDialog1.SelectedPath, szName, reportViewer2);

                    break;
            }

            ChangeStateButtons(true);
        }
        else 
        {
            MessageBox.Show("El rango de fechas debe ser máximo de 3 meses");
        }
    }

    void RenderReportC(string szPath,string szFileName,ReportViewer pReporter)
    {
      Warning[] warnings;
      string[] streamids;
      string mimeType;
      string encoding;
      string extension;

      byte[] bytes = pReporter.LocalReport.Render(
         "Excel", null, out mimeType, out encoding,
          out extension,
         out streamids, out warnings);

      FileStream fs = new FileStream(szPath + "\\" + szFileName, FileMode.Create);
      fs.Write(bytes, 0, bytes.Length);
      fs.Close();

      //Label1.Text = "Report exported to output.xls";

    }

    private void botonGeneraMultiple_Click(object sender, EventArgs e)
    {
        ReporteGrupal();
    }

    void ReporteMultipleExcel() 
    {
        //procedimiento de generacion de multiples reportes
        //genera reporte
        CPersonal pPersonal = null;
        CVehicle pVehicle = null;
        List<CMarkRegister> lListMarks = null;
        CMarkReportItem pReportItem = null;
        string szDates, szName;
        int iCounter;
        TimeSpan tsTimeWorked;

        ChangeStateButtons(false);

        dateTimePickerDesde.Value = dateTimePickerDesde.Value.Date +
                        (new TimeSpan(dateTimePickerDesde.Value.Hour, dateTimePickerDesde.Value.Minute, 0));
        dateTimePickerHasta.Value = dateTimePickerHasta.Value.Date +
                        (new TimeSpan(dateTimePickerHasta.Value.Hour, dateTimePickerHasta.Value.Minute, 59));


        if (dateTimePickerDesde.Value > dateTimePickerHasta.Value)
        {
            //busqueda por fechas invalida
            MessageBox.Show(this, "La fecha de inicio debe ser menor a la fecha final", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            ChangeStateButtons(true);
            return;
        }

        szDates = dateTimePickerDesde.Value.ToString("yyyy/MM/dd hh:mm tt") + " - " + dateTimePickerHasta.Value.ToString("yyyy/MM/dd hh:mm tt");

        if (lListVehicle != null)
        {
            if (lListVehicle.Count == 0)
            {
                MessageBox.Show(this, "Seleccione resultados para reportar", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ChangeStateButtons(true);
                return;
            }

        }

        //Destino de los reportes

        DialogResult dResult = folderBrowserDialog1.ShowDialog();

        if (dResult == DialogResult.Cancel)
        {
            ChangeStateButtons(true);

            return;
        }

        switch (iLastResult)
        {
            case W_LAST_RESULT_PERSONAL:
                for (iCounter = 0; iCounter < lListPersonal.Count; iCounter++)
                {
                    lListReportItems.Clear();
                    pPersonal = lListPersonal[iCounter];
                    lListMarks = pVWise_DAO_Access.SearchMarks(CMarkRegister.VWISE_DHL_PERSONAL,
                                                               pPersonal.iPKCode,
                                                               dateTimePickerDesde.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                                                               dateTimePickerHasta.Value.ToString("yyyy-MM-dd HH:mm:ss"));

                    if (lListMarks == null)
                    {
                        MessageBox.Show(this, "No se encontraron registros para: " + pPersonal.szPatLastName +
                                              " " + pPersonal.szMatlastName + ", " + pPersonal.szFirstName, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        continue;
                    }

                    //if (lListMarks.Count == 0)
                    //{
                    //  MessageBox.Show(this, "No se encontraron registros", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    //  botonGenerar.Enabled = true;
                    //  botonBuscar.Enabled = true;
                    //  return;
                    //}

                    //calculo de horas trabajadas
                    //CalculateHorasDeTrabajo

                    if (lListMarks.Count == 0)
                    {
                        pReportItem = new CMarkReportItem();

                        pReportItem.pMarkRegister = new CMarkRegister(CMarkRegister.VWISE_DHL_PERSONAL);

                        pReportItem.pPersonal = pPersonal;

                        pReportItem.szDates = szDates;

                        pReportItem.tsTiempoTrabajado = new TimeSpan(0);

                        lListReportItems.Add(pReportItem);
                    }
                    else
                    {
                        //calculo de horas trabajadas
                        tsTimeWorked = CalculateHorasDeTrabajo(pPersonal, lListMarks);

                        foreach (CMarkRegister pMark in lListMarks)
                        {
                            pReportItem = new CMarkReportItem();

                            pReportItem.pMarkRegister = pMark;

                            pReportItem.pPersonal = pPersonal;

                            pReportItem.szDates = szDates;

                            pReportItem.tsTiempoTrabajado = tsTimeWorked;

                            lListReportItems.Add(pReportItem);
                        }
                    }



                    bindingSource1.DataSource = lListReportItems;

                    reportViewer3.RefreshReport();
                    reportViewer3.Visible = true;
                    reportViewer2.Visible = false;
                    reportViewer1.Visible = false;
                    szName = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss") + pPersonal.szPatLastName + " " + pPersonal.szMatlastName +
                              " " + pPersonal.szFirstName + ".xls";
                    RenderReportC(folderBrowserDialog1.SelectedPath, szName, reportViewer1);
                }

                break;

            case W_LAST_RESULT_VEHICLE:
                for (iCounter = 0; iCounter < lListVehicle.Count; iCounter++)
                {
                    lListReportItems.Clear();

                    pVehicle = lListVehicle[iCounter];

                    lListMarks = pVWise_DAO_Access.SearchMarks(CMarkRegister.VWISE_DHL_VEHICLE,
                                                               pVehicle.iPKCode,
                                                               dateTimePickerDesde.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                                                               dateTimePickerHasta.Value.ToString("yyyy-MM-dd HH:mm:ss"));

                    if (lListMarks == null)
                    {
                        MessageBox.Show(this, "No se encontraron registros para: " + pVehicle.szPlaca, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        continue;
                    }

                    if (lListMarks.Count == 0)
                    {
                        pReportItem = new CMarkReportItem();

                        pReportItem.pMarkRegister = new CMarkRegister(CMarkRegister.VWISE_DHL_VEHICLE);

                        pReportItem.pVehicle = pVehicle;

                        pReportItem.szDates = szDates;

                        lListReportItems.Add(pReportItem);
                    }
                    else
                    {

                        foreach (CMarkRegister pMark in lListMarks)
                        {
                            pReportItem = new CMarkReportItem();

                            pReportItem.pMarkRegister = pMark;

                            pReportItem.pVehicle = pVehicle;

                            pReportItem.szDates = szDates;

                            lListReportItems.Add(pReportItem);
                        }
                    }



                    CMarkReportItemBindingSource.DataSource = lListReportItems;
                    reportViewer2.RefreshReport();

                    szName = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss") + pVehicle.szPlaca + ".xls";

                    RenderReportC(folderBrowserDialog1.SelectedPath, szName, reportViewer2);


                }
                break;
        }

        ChangeStateButtons(true);
    }

    private void grBoxBusqueda_Enter(object sender, EventArgs e)
    {

    }

    private void textArea_SelectedIndexChanged(object sender, EventArgs e)
    {
        

        
    }

    private void textArea_SelectedValueChanged(object sender, EventArgs e)
    {

        int codDepartamento = 0;
        if (textArea.SelectedValue is Department)
        {
            codDepartamento = ((Department)textArea.SelectedValue).department_id;
        }
        else
        {
            if (textArea.SelectedValue is int)
            {
                codDepartamento = (int)textArea.SelectedValue;
            }
        }


        var bd = new DHLDataContextDataContext();

        List<Department> listaArea = (from d in bd.Departments
                                     where d.department_manager_cd == codDepartamento
                                     select d).ToList();
        comboArea.DataSource = listaArea;
        comboArea.ValueMember = "department_id";
        comboArea.DisplayMember = "department_nm";
    }

    private void comboArea_SelectedIndexChanged(object sender, EventArgs e)
    {
        int codDepartamento = 0;
        int codArea = 0;
        if (textArea.SelectedValue is Department)
        {
            codDepartamento = ((Department)textArea.SelectedValue).department_id;
        }
        else
        {
            if (textArea.SelectedValue is int)
            {
                codDepartamento = (int)textArea.SelectedValue;
            }
        }

        if (comboArea.SelectedValue is Department)
        {
            codArea = ((Department)comboArea.SelectedValue).department_id;
        }
        else
        {
            if (comboArea.SelectedValue is int)
            {
                codArea = (int)comboArea.SelectedValue;
            }
        }

        var bd = new DHLDataContextDataContext();

        List<Department> listaSeccion = (from d in bd.Departments
                                           where d.department_manager_cd==codArea
                                           select d).ToList();
        comboSeccion.DataSource = listaSeccion;
        comboSeccion.ValueMember = "department_id";
        comboSeccion.DisplayMember = "department_nm";
    }

    private void textArea_SelectedIndexChanged_1(object sender, EventArgs e)
    {

    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {

    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox1.Checked)
        {
            textArea.Enabled = true;
            comboArea.Enabled = true;
            comboSeccion.Enabled = true;
        }
        else 
        {
            textArea.Enabled = false;
            comboArea.Enabled = false;
            comboSeccion.Enabled = false;
        }
    }
  }
}
